#!/bin/bash

# ================================
# Docker + 镜像加速器 一键安装脚本 for CentOS 7
# Author: AI助手
# ================================

echo "🚀 开始安装 Docker 和配置阿里云镜像加速器..."

# 1. 卸载旧版本 Docker（如存在）
sudo yum remove -y docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine

# 2. 安装依赖
sudo yum install -y yum-utils \
  device-mapper-persistent-data \
  lvm2

# 3. 添加阿里云 Docker CE 源
sudo yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

# 4. 安装 Docker CE
sudo yum install -y docker-ce docker-ce-cli containerd.io

# 5. 启动 Docker 并设置开机自启
sudo systemctl start docker
sudo systemctl enable docker

# 6. 获取用户输入的阿里云加速器地址
read -p "请输入你的阿里云容器镜像服务加速器地址（例如：https://xxxxx.mirror.aliyuncs.com ）：" MIRROR_URL

# 7. 配置镜像加速器
sudo tee /etc/docker/daemon.json <<EOF
{
  "registry-mirrors": ["$MIRROR_URL"]
}
EOF

# 8. 重启 Docker 以应用配置
sudo systemctl daemon-reload
sudo systemctl restart docker

# 9. 验证是否成功
echo "🐋 正在验证 Docker 是否安装成功..."
docker --version
docker run hello-world

# 10. （可选）安装 Docker Compose
read -p "是否安装 Docker Compose？(y/n): " INSTALL_COMPOSE
if [[ "$INSTALL_COMPOSE" == "y" || "$INSTALL_COMPOSE" == "Y" ]]; then
  echo "📦 正在安装 Docker Compose..."
  sudo curl -L "https://ghproxy.com/github.com/docker/compose/releases/download/v2.23.0/docker-compose- $(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
  sudo chmod +x /usr/local/bin/docker-compose
  docker-compose --version
fi

echo "✅ Docker 安装和配置已完成！"
